/*
 * @Author: huangyingli
 * @Date: 2022-10-20 15:06:31
 * @LastEditors: huangyingli
 * @LastEditTime: 2022-12-13 17:45:40
 * @Description:
 */
const { underscore } = require('naming-style');
const { resError, resSuccess } = require('../../utils/response');

function searchSiteConfig(connection, cb) {
  connection.query(
    'select * from site_config',
    function (error, results, fields) {
      if (error) {
        cb(resError(error));
        return;
      }
      cb(resSuccess(results[0]));
    }
  );
}

function setSiteConfig(connection, data, cb) {
  let { title, keywords, icon, logo } = data;
  connection.query(
    `update  site_config set title = "${title}", keywords = "${keywords}", icon = "${icon}", logo = "${logo}" where id = 0;`,
    function (error, results) {
      if (error) {
        cb(resError(error));
        return;
      }
      cb(resSuccess());
    }
  );
}

function getModalMange(connection, cb) {
  connection.query('select * from modal_manager', (error, results) => {
    if (error) {
      cb(resError(error));
      return;
    }
    cb(resSuccess(results));
  });
}

function setModalManage(connection, data, cb) {
  let { modal_name, table_name, modal_config, modal_file } = data;
  connection.query(
    `INSERT into modal_manager(modal_name, modal_layout, modal_components) values ("${modal_name}", "${modal_config}", "${table_name}", "${modal_file}");`,
    (error, results) => {
      if (error) {
        cb(resError(error));
        return;
      }
      cb(resSuccess());
    }
  );
}

function getColumnManage(connection, cb) {
  connection.query('select * from column_manager', function (error, results) {
    if (error) {
      cb(resError(error));
      return;
    }
    cb(resSuccess(results));
  });
}

function setColumnManage(connection, data, cb) {
  let { title, route, parent, modal, page } = data;
  connection.query(
    `insert into column_manager(title, route, parent, modal, page) values ("${title}", "${route}", "${parent}", "${modal}", "${page}")`,
    (error, result) => {
      if (error) {
        cb(resError(error));
        return;
      }
      cb(resSuccess(result));
    }
  );
}

function getContentManage(connection, cb) {
  connection.query('select * from column_manager', function (error, results) {
    if (error) {
      cb(resError(error));
      return;
    }
    cb(resSuccess(results));
  });
}

function getPageConfigByModal(connection, modal, cb) {
  connection.query(
    `select * from modal_manager where modal_name = "${modal}";`,
    (error, results) => {
      if (error) {
        cb(resError(error));
        return;
      }
      cb(resSuccess(results[0]));
    }
  );
}

function getContentData(connection, table, columnId, modalId, subName, cb) {
  connection.query(
    `select * from ${table} where column_id = '${columnId}' and modal_id = '${modalId}' and sub_name = '${subName}';`,
    (error, results) => {
      if (error) {
        cb(resError(error));
        return;
      }
      cb(resSuccess(results[0]));
    }
  );
}

function setContentData(connection, table, id, data, cb) {
  let keys = Object.keys(data);

  let values = '';
  keys.forEach((key, idx) => {
    values += `${underscore(key)}='${data[key]}'${
      idx == keys.length - 1 ? '' : ','
    }`;
  });

  let query;

  if (id) {
    query = `UPDATE ${table} set ${values} where id = "${id}"`;
  } else {
    query = `INSERT into ${table}(${Object.keys(data)
      .map((k) => underscore(k))
      .join(', ')}) values (${Object.values(data)
      .map((d) => `'${d}'`)
      .join(', ')});`;
  }
  console.log('query', query);
  connection.query(query, (error, result) => {
    if (error) {
      cb(resError(error));
      return;
    }
    cb(resSuccess(result));
  });
}

function getManagerList(connection, table, cb) {
  connection.query(`select * from ${table}`, function (error, results) {
    if (error) {
      cb(resError(error));
      return;
    }
    cb(resSuccess(results));
  });
}

function setManagerList(connection, table, data, isAdd, cb) {
  let query;
  if (isAdd) {
    query = `INSERT into ${table}(${Object.keys(data)
      .map((k) => underscore(k))
      .join(', ')}) values (${Object.values(data)
      .map((d) => `'${d}'`)
      .join(', ')});`;
  } else {
  }
  console.log('query', query);
  connection.query(query, (error, result) => {
    if (error) {
      cb(resError(error));
      return;
    }
    cb(resSuccess());
  });
}

const mapType = {
  string: 'CHAR(100)',
  number: 'INT',
  array: 'TEXT'
};

const allowNull = (required) => (!required ? '' : 'NOT NULL');

function createTableFromConfig(connection, tableName, config, cb) {
  let content = [];
  console.log('config', config);
  for (k in config) {
    let { label, key, required, type } = config[k].form;
    content.push(
      `${underscore(key)} ${mapType[type]} ${allowNull(
        required
      )} COMMENT '${label}'`
    );
  }
  content.push(`id INT NOT NULL AUTO_INCREMENT`, `PRIMARY KEY (id)`);
  content.push(`column_id CHAR(50) NOT NULL`);
  content.push(`modal_id CHAR(50) NOT NULL`);
  content.push(`sub_name CHAR(50) NOT NULL`);
  let query = `CREATE TABLE ${tableName} (${content.join(',')})`;

  console.log('query', query);

  connection.query(query, (error) => {
    cb(error ? true : false);
  });
}

function getComponentsByIds(connection, ids, cb) {
  let query = `SELECT * from component_manager where ${ids
    .map((id) => `id = ${id}`)
    .join(' OR ')}`;

  console.log('query', query);

  connection.query(query, (error, result) => {
    if (error) {
      cb(resError(error));
      return;
    }
    cb(resSuccess(result));
  });
}

function getColumnByRoute(connection, route, cb) {
  connection.query(
    `SELECT * from column_manager where route = '${route}'`,
    (error, result) => {
      cb(result[0]);
    }
  );
}

module.exports = {
  searchSiteConfig,
  setSiteConfig,
  getModalMange,
  setModalManage,
  getColumnManage,
  getContentManage,
  getPageConfigByModal,
  getContentData,
  setColumnManage,
  setContentData,

  getManagerList,
  setManagerList,

  createTableFromConfig,

  getComponentsByIds,
  getColumnByRoute,
};
